package com.iwhalecloud.bss.kite.cucc.web.controller.goods;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.GoodsUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsModifyService;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.AttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodPriceReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsCategroyInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsMemberDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsParamDTO;
import com.iwhalecloud.bss.kite.cucc.web.service.goods.modify.GoodsModifyServiceEnum;
import com.iwhalecloud.bss.kite.cucc.web.service.goods.modify.GoodsModifyServiceFactory;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "/goods - 商品" })
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @ApiOperation(value = "收发端成员查询", notes = "收发端成员查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "goodsSku", value = "商品id", required = true)
    })
    @PostMapping("/members")
    public DataResult<List<GoodsMemberDTO>> queryGoodsMember(@RequestParam(required = true) String goodsSku) {
        return goodsService.queryGoodsMember(goodsSku);
    }
    @ApiOperation(value = "新·商品分类查询", notes = "新·商品分类查询")
    @GetMapping("/goodsCategroyInfo")
    public DataResult<List<GoodsCategroyInfoDTO>> queryGoodsCategroyInfo(
        @RequestParam(required = true) String goodsProvice, @RequestParam(required = false) String orderCatagoryId) {
        List<GoodsCategroyInfoDTO> list = goodsService.queryGoodsCategroyInfo(goodsProvice);

        // orderCatagoryId：互联网意向单需求使用，尽可选择互联网产品，将可选目录配置到数据库，进行过滤
        if(KiteListUtils.isNotEmpty(list) && KiteStringUtils.isNotEmpty(orderCatagoryId)) {
            String codea = DcPublicCache.getCodea("20210914001", orderCatagoryId);
            if(KiteStringUtils.isNotEmpty(codea)) {
                String[] selectableIdArr = codea.split(SymbolConsts.COMMA);

                removeGoodCateId(list, selectableIdArr);
            }
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "新·根据商品类别、商品名称查询商品列表", notes = "新·根据商品类别、商品名称查询商品列表")
    @PostMapping("/goodsListInCategroy")
    public DataResult<List<GoodsDTO>> queryGoodsListInCategroy(@RequestBody GoodsParamDTO goodsParamDTO) {
        List<GoodsDTO> list = goodsService.queryGoodsListInCategroy(goodsParamDTO.getCategroyCode(), goodsParamDTO.getGoodsName());

        if(KiteListUtils.isNotEmpty(list) && KiteStringUtils.isNotEmpty(goodsParamDTO.getOrderCatagoryId())) {
            String codea = DcPublicCache.getCodea("20210914001", goodsParamDTO.getOrderCatagoryId());
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] selectableIdArr = codea.split(SymbolConsts.COMMA);
                for (int i = list.size() - 1; i >= 0; i--) {
                    if(!KiteStringUtils.equalsAny(list.get(i).getCateId(), selectableIdArr)) {
                        list.remove(i);
                    }
                }
            }
        }

        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "新·产商品详情查询", notes = "新·产商品详情查询")
    @PostMapping("/queryGoodsInfo")
    public DataResult<Map<String, Object>> queryGoodsInfo(@RequestParam String goodsSku) {
        Map<String, Object> dto = goodsService.queryGoodsByOfferId(goodsSku);
        return ErrorConsts.SUCCESS.getResult(dto);
    }

    @ApiOperation(value = "新·商品属性查询", notes = "新·商品属性查询")
    @GetMapping("/keyAtts")
    public DataResult<List<AttrDTO>> queryGoodKeyAttrs(@RequestParam String goodsSku,@RequestParam(required = false) String serviceOfferId) {
        DataResult<List<AttrDTO>> result =  goodsService.queryGoodKeyAttrsByProvince(goodsSku);
        GoodsUtil.checkAndFilterGoods(result.getResultObject(),serviceOfferId,goodsSku);
        return result;
    }

    @ApiOperation(value = "新·商品价格查询", notes = "新·商品价格查询")
    @PostMapping("/price")
    public DataResult<String> queryGoodPrice(@RequestBody GoodPriceReqDTO goodPriceReqDTO) {
        return goodsService.queryGoodPrice(goodPriceReqDTO);
    }

    @ApiOperation(value = "新·产商品详情查询(基础)", notes = "新·产商品详情查询(基础)")
    @PostMapping("/queryBaseGoodsInfoNew")
    public DataResult<List<GoodsDTO>> queryBaseGoodsInfoNew(@RequestParam String goodsName, @RequestParam String categroyCode) {
        List<GoodsDTO> dtos = goodsService.queryBaseGoodsInfoNew(goodsName, categroyCode);
        return ErrorConsts.SUCCESS.getResult(dtos);
    }

    @ApiOperation(value = "新·查询收藏列表", notes = "新·查询收藏列表")
    @PostMapping("/queryFavoriteGoodsList")
    public DataResult<List<Map<String,Object>>> queryFavoriteGoodsList(@RequestBody GoodsParamDTO goodsParamDTO) {
        List<Map<String,Object>> list = goodsService.queryFavoriteGoodsList(goodsParamDTO.getGoodsName());

        if(KiteListUtils.isNotEmpty(list) && KiteStringUtils.isNotEmpty(goodsParamDTO.getOrderCatagoryId())) {
            String codea = DcPublicCache.getCodea("20210914001", goodsParamDTO.getOrderCatagoryId());
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] selectableIdArr = codea.split(SymbolConsts.COMMA);
                for (int i = list.size() - 1; i >= 0; i--) {
                    if(!KiteStringUtils.equalsAny(MapUtils.getString(list.get(i), "cateId"), selectableIdArr)) {
                        list.remove(i);
                    }
                }
            }
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "操作收藏套餐", notes = "操作收藏套餐")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "offerId", value = "销售品标识", required = true),
        @ApiImplicitParam(name = "actionType", value = "动作", required = true)
    })
    @PostMapping(value = "/operateFavoritesOffers")
    public DataResult<Map<String, Object>> operateFavoritesOffers(@RequestParam String offerId, @RequestParam String actionType) {
        return ErrorConsts.SUCCESS.getResult(goodsService.operateFavoritesOffers(offerId,actionType));
    }

    @ApiOperation(value = "新·查询最近受理商品列表", notes = "新·查询最近受理商品列表")
    @PostMapping("/queryLatestAcceptList")
    public DataResult<List<GoodsDTO>> queryLatestAcceptList(@RequestParam(required = false) String orderCatagoryId) {
        List<GoodsDTO> list = goodsService.queryLatestAcceptList();

        if(KiteListUtils.isNotEmpty(list) && KiteStringUtils.isNotEmpty(orderCatagoryId)) {
            String codea = DcPublicCache.getCodea("20210914001", orderCatagoryId);
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] selectableIdArr = codea.split(SymbolConsts.COMMA);
                for (int i = list.size() - 1; i >= 0; i--) {
                    if(!KiteStringUtils.equalsAny(list.get(i).getCateId(), selectableIdArr)) {
                        list.remove(i);
                    }
                }
            }
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "获取可变更的商品列表", notes = "获取可变更的商品列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "offerId", value = "销售品标识", required = true),
        @ApiImplicitParam(name = "cateId", value = "分类ID", required = false)
    })
    @GetMapping(value = "/exchangeableGoodsList")
    public DataResult<List<GoodsDTO>> exchangeableGoodsList(@RequestParam String offerId, @RequestParam(required = false) String cateId) {
        if (KiteStringUtils.isEmpty(cateId)) {
            cateId = Optional.ofNullable(OfferCache.get(offerId)).map(Offer::getCateId).orElse("");
            if (KiteStringUtils.isEmpty(cateId)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("找不到当前套餐的规格数据，请检查");
            }
        }
        IGoodsModifyService iGoodsModifyService = GoodsModifyServiceFactory.getInstance(GoodsModifyServiceEnum.codeOf(cateId));
        return ErrorConsts.SUCCESS.getResult(iGoodsModifyService.queryTargetGoodsList(offerId,cateId));
    }

    @ApiOperation(value = "获取变更商品的关键属性列表", notes = "获取变更商品的关键属性列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "offerId", value = "销售品标识", required = true),
        @ApiImplicitParam(name = "cateId", value = "分类ID", required = false)
    })
    @GetMapping(value = "/keyAttrsForGoodsModify")
    public DataResult<List<AttrDTO>> keyAttrsForGoodsModify(@RequestParam String offerId, @RequestParam(required = false) String cateId) {
        if (KiteStringUtils.isEmpty(cateId)) {
            cateId = Optional.ofNullable(OfferCache.get(offerId)).map(Offer::getCateId).orElse("");
            if (KiteStringUtils.isEmpty(cateId)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("找不到当前套餐的规格数据，请检查");
            }
        }
        IGoodsModifyService iGoodsModifyService = GoodsModifyServiceFactory.getInstance(GoodsModifyServiceEnum.codeOf(cateId));
        return ErrorConsts.SUCCESS.getResult(iGoodsModifyService.queryGoodKeyAttrs(offerId));
    }

    @ApiOperation(value = "新·商品末级分类查询", notes = "新·商品末级分类查询")
    @GetMapping("/goodsCategroyLastStageInfo")
    public DataResult<List> queryGoodsCategroyLastStageInfo(
        @RequestParam(required = true) String goodsProvice) {
        List<Map> list = goodsService.queryGoodsCategroyLastStageInfo(goodsProvice);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "新·商品属性查询", notes = "新·商品属性查询")
    @GetMapping("/queryGoodAttrs")
    public DataResult<List<AttrDTO>> queryGoodAttrs(@RequestParam(required = true) String goodsSku) {
        return goodsService.queryGoodsAttrsByProvince(goodsSku);
    }

    @ApiOperation(value = "app甩单商品关键属性查询", notes = "app甩单商品关键属性查询")
    @GetMapping("/queryAppOrderGoodAttrs")
    public DataResult<Map<String, Object>> queryAppOrderGoodAttrs(@RequestParam String orderId) {
        Map<String, Object> result = goodsService.queryAppOrderGoodAttrs(orderId);
        return ErrorConsts.SUCCESS.getResult(result);
    }

    private static void removeGoodCateId(List<GoodsCategroyInfoDTO> child, String[] selectableIdArr) {
        for (int i = child.size() - 1; i >= 0 ; i--) {
            if(!KiteStringUtils.equalsAny(child.get(i).getNodeCode(), selectableIdArr)) {
                child.remove(i);
                continue;
            }

            List<GoodsCategroyInfoDTO> child2 = child.get(i).getChild();
            if(KiteListUtils.isNotEmpty(child2)) {
                removeGoodCateId(child2, selectableIdArr);
            }
        }
    }
}
